﻿using Microsoft.AspNetCore.Mvc;

namespace DailyReport.Server.Service;

/// <summary>
/// 
/// </summary>
[ApiExplorerSettings(GroupName = "DailyReport")]
public partial class DailyService : IApplicationService
{
    private readonly SugarRepository<ReportDetail> _thisRepository;
    private readonly ICurrentUser _currentUser;

    public DailyService(SugarRepository<ReportDetail> thisRepository, ICurrentUser currentUser)
    {
        _thisRepository = thisRepository;
        _currentUser = currentUser;
    }

    public async Task<RestfulResult<PageResult<ReportDetailOutDto>>> GetPagesAsync(PageParam data)
    {
        var restful = new RestfulResult<PageResult<ReportDetailOutDto>> { Code = CodeStatus.OK };

        DateTime beginTime = data.BeginTime ?? DateTime.Now.AddDays(-25);
        DateTime endTime = data.EndTime ?? DateTime.Now.AddDays(5);

        var query = await _thisRepository.AsQueryable()
            .Where(u => u.Creator == _currentUser.UserId)
            .Where(u => u.Category == Category.Day)
            .Where(u => SqlFunc.Between(u.Day, beginTime, endTime))
            .OrderByDescending(u => u.Day)
            .Select(u => new ReportDetailOutDto
            {
                Id = u.Id,
                Day = u.Day,
                Content = u.Content
            })
            .ToPageAsync(data.PageNo, data.PageSize);

        restful.Data = query;
        return restful;
    }

    public async Task<RestfulResult> SubmitAsync(ReportDetail data)
    {
        RestfulResult restful = new() { Code = CodeStatus.BadRequest };
        bool result = false;

        if (data.Id == 0)
        {
            data.Category = Category.Day;
            data.IsDelete = IsDelete.N;
            data.Month = data.Day.Month;
            result = await _thisRepository.InsertAsync(data);
        }
        else
        {
            result = await _thisRepository.UpdateAsync(data);
        }

        if (result)
        {
            restful.Code = CodeStatus.OK;
            restful.Data = result;
        }
        else
        {
            restful.Data = result;
        }

        return restful;
    }
}
